package kr.hkit.powerjava.chapter24.submit3;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Student_Dao implements Interface_Dao<Student_Vo>{

	private ArrayList<Student_Vo> lists ; //lists로 해야 스튜,디파트 다 쓸수있음
	private final String filePath = "stdList.data"; //파일 이름 여기서 지정
	
	
	@Override
	public void insertItem(Student_Vo item) { //삽입
		if (!lists.contains(item)) { //false면. 없으면 삽입
		lists.add(item);
		}
	}

	@Override
	public void deleteItem(Student_Vo item) { //삭제
		if (lists.contains(item)) { //존재하면 삭제
		lists.remove(item); 
		}
	}

	@Override
	public void updateItem(Student_Vo item) { //수정
		if (lists.contains(item)) { //존재하면
			lists.set(lists.indexOf(item), item);
		}
	}
	
	@Override
	public Student_Vo searchItem(Student_Vo item) { //검색
		Student_Vo searchValue = null;
		if (lists.contains(item)) { //검색하면 그사람정보 다 나오게
			searchValue = lists.get(lists.indexOf(item));
		}
		return searchValue;
	}

	
	
	@Override
	public void prnItem(Comparator<Student_Vo> comp) { //출력. //정렬순으로도 해야함
		if (comp==null) {
			Collections.sort(lists); //이건 그냥 번호순으로 정렬되니까
		} else {
			Collections.sort(lists, comp);
		}
		for (Student_Vo l : lists) {
			System.out.println(l);
		}
	}
	
	/*public void prnHeader() {
		String header = String.format("%3s\t%5s\t%2s\t%2s\t%2s\t%3s\t%6.2f",
				"학번", "이름", "국어", "영어", "수학", "총점", "평균");
		System.out.println(header);
	}*/

	@Override
	public void loadFile() { //파일 읽기 저장.
		ObjectInputStream ois = null;
		
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filePath)));
			lists = (ArrayList<Student_Vo>) ois.readObject(); //여긴 있으니까 arraylist 생성안해도돼
			
		} catch (FileNotFoundException e) { //없을경우에는 생성
			try {
				new File(filePath).createNewFile();
				lists = new ArrayList<Student_Vo>(); //없으니까 arraylist생성해줌. 
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null) {
				try {ois.close();} catch (IOException e) {}
			}
		}
	}

	@Override
	public void saveFile() { //덮어쓰기 ?
		ObjectOutputStream oos = null;
		
		try {
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filePath)));
			oos.writeObject(lists);
		} catch (FileNotFoundException e) {
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (oos != null) {
				try {oos.close();} catch (IOException e) {}
			}
		}
	}

	
}
